#!/bin/bash

# Copyright (c) 2025-2025 Huawei Cloud Computing Technology Co., Ltd. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this list of
#    conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice, this list
#    of conditions and the following disclaimer in the documentation and/or other materials
#    provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its contributors may be used
#    to endorse or promote products derived from this software without specific prior written
#    permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

# 设置MY_OHOS_DIR为脚本所在目录的上级目录的上级目录
# (假设脚本放在third_party/iot_device_sdk_c目录下)

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
echo "SCRIPT_DIR为：$SCRIPT_DIR"

# 检查目录结构是否正确
if [ ! -d "$SCRIPT_DIR" ]; then
    echo "错误：脚本应该放在 $SCRIPT_DIR 目录下"
    exit 1
fi

# 进入iot_device_sdk_c目录
cd "$SCRIPT_DIR" || {
    echo "错误：无法进入$SCRIPT_DIR目录"
    exit 1
}

if [ -d "$SCRIPT_DIR/third_party" ]; then
    echo "警告：$SCRIPT_DIR/third_party已存在，正在删除..."
    rm -rf third_party || {
        echo "错误，无法删除旧目录"
        return 1
    }
fi

# 创建third_party目录
mkdir -p third_party || {
    echo "错误：无法创建third_party目录"
    exit 1
}
# 进入third_party目录
cd third_party || {
    echo "错误：无法进入third_party目录"
    exit 1
}

setup_git() {
    git config --global http.postBuffer 524288000
    git config --global http.sslVerify false
    echo "git config --global http.sslVerify false"
	
	# 定义需要添加/修改的映射数组
	declare -A mappings=(
		["github.com"]="140.82.114.4"
		["api.github.com"]="140.82.114.4"
	)

	# 检查是否以root运行
	if [ "$(id -u)" -ne 0 ]; then
		echo "错误：此脚本必须以root权限运行" >&2
		return 1
	fi

	# 备份原始hosts文件
	cp /etc/hosts /etc/hosts.bak.$(date +%Y%m%d%H%M%S)
	echo "已创建备份：/etc/hosts.bak.*"

	# 处理每个域名
	for domain in "${!mappings[@]}"; do
		ip="${mappings[$domain]}"
		# 检查域名是否存在
		if grep -qE "^\s*[0-9.]{7,15}\s+$domain(\s|$)" /etc/hosts; then
			# 存在则更新映射
			sed -i -E "s/^(\s*)[0-9.]{7,15}(\s+$domain(\s|$))/\1$ip\2/" /etc/hosts
			echo "已更新: $domain → $ip"
		else
			# 不存在则添加新映射
			echo -e "$ip\t$domain" >> /etc/hosts
			echo "已添加: $domain → $ip"
		fi
	done

	echo "操作完成。当前映射："
	grep -E 'github.com|api.github.com' /etc/hosts
	
	sudo service network-manager restart
	
	# 检查CMake是否已安装
	if command -v cmake &> /dev/null; then
		echo "CMake 已安装: $(cmake --version | head -n 1)"
		return 0
	fi

	# 检查包管理器并安装CMake
	if command -v apt-get &> /dev/null; then
		# Debian/Ubuntu
		echo "使用 apt 安装 CMake..."
		sudo apt-get update
		sudo apt-get install -y cmake
	fi
	# 验证安装
	if command -v cmake &> /dev/null; then
		echo "CMake 安装成功: $(cmake --version | head -n 1)"
	else
		echo "安装失败！请手动安装CMake"
		exit 1
	fi
}
show_status() {
    echo "------------------------------------------------"
    grep -E 'github.com|api.github.com' /etc/hosts || echo "未找到 GitHub 相关映射"
    echo "------------------------------------------------"
    echo "所有备份文件:"
	ls -l /etc/hosts.bak.* 2>/dev/null || echo "无备份文件"
}
# 恢复备份
setdome_git() {
    # 检查root权限
    [ "$(id -u)" -ne 0 ] && { echo "错误：此操作需要root权限"; exit 1; }
    
    local latest_backup=$(ls -t /etc/hosts.bak.* 2>/dev/null | head -1)
    
    if [ -z "$latest_backup" ]; then
        echo "找不到备份文件"
        return 1
    fi
    
    cp -f "$latest_backup" /etc/hosts
    echo "已从备份恢复: $latest_backup"
    
    echo -e "\n当前映射状态:"
    show_status
	sudo service network-manager restart
}

# 克隆仓库函数

# 克隆仓库函数
clone_repo() {
    local repo_url=$1
    local repo_name=$(basename "${repo_url%.git}")
    local branch_option=$2
    local retries=10
	local delay=10
	
    echo "正在克隆仓库: $repo_name"
    if [ -z "$branch_option" ]; then
        for ((i=1; i<=retries; i++)); do
			git clone "$repo_url" && {
				echo "克隆成功!"
				break
			}
			
			echo "尝试 $i/$retries 失败，${delay}秒后重试..."
			sleep $delay
		done
    else
		for ((i=1; i<=retries; i++)); do
			git clone $branch_option "$repo_url" && {
				echo "克隆成功!"
				break
			}
			echo "尝试 $i/$retries 失败，${delay}秒后重试..."
			sleep $delay
		done
		
    fi 
    # 检查克隆后的目录是否存在
    if [ ! -d "$repo_name" ]; then
        echo "错误：克隆后目录 $repo_name 不存在"
        return 1
    fi
    
    echo "成功克隆仓库: $repo_name"
    return 0
}

setup_git

# 克隆所有仓库

clone_repo "https://gitee.com/Janisa/huawei_secure_c.git" || exit 1

git config --global http.sslVerify false
clone_repo "https://github.com/eclipse/paho.mqtt.c.git" "-b v1.3.12 --single-branch" || exit 1
clone_repo "https://git.libssh.org/projects/libssh.git" "-b libssh-0.9.6 --single-branch" || exit 1

git config --global http.sslVerify false
clone_repo "https://github.com/ASPLes/nopoll.git" "-b 0.4.8 --single-branch" || exit 1

git config --global http.sslVerify true
setdome_git

# 创建BUILD.gn文件函数
create_build_gn() {
    local dir=$1
    local content=$2
    
    echo "正在为 $dir 创建BUILD.gn文件..."
    
    # 检查目标目录是否存在
    if [ ! -d "$dir" ]; then
        echo "错误：目录 $dir 不存在"
        return 1
    fi
    
    # 创建文件
    echo "$content" > "$dir/BUILD.gn" || {
        echo "错误：无法创建 $dir/BUILD.gn 文件"
        return 1
    }
    
    # 验证文件是否创建成功
    if [ ! -f "$dir/BUILD.gn" ]; then
        echo "错误：BUILD.gn 文件创建失败"
        return 1
    fi
    
    echo "成功创建 $dir/BUILD.gn"
    return 0
}

# 为huawei_secure_c创建BUILD.gn文件
echo "创建huawei_secure_c/BUILD.gn..."
huawei_secure_c_content='
#
# Copyright (c) [2020] Huawei Technologies Co.,Ltd.All rights reserved.
#
# OpenArkCompiler is licensed under the Mulan PSL v1.
# You can use this software according to the terms and conditions of the Mulan PSL v1.
# You may obtain a copy of Mulan PSL v1 at:
#
#     http://license.coscl.org.cn/MulanPSL
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR
# FIT FOR A PARTICULAR PURPOSE.
# See the Mulan PSL v1 for more details.
#
import("//build/ohos.gni")

src_libHWSecureC = [
  "src/vsprintf_s.c",
  "src/wmemmove_s.c",
  "src/strncat_s.c",
  "src/vsnprintf_s.c",
  "src/fwscanf_s.c",
  "src/scanf_s.c",
  "src/strcat_s.c",
  "src/sscanf_s.c",
  "src/secureprintoutput_w.c",
  "src/wmemcpy_s.c",
  "src/wcsncat_s.c",
  "src/secureprintoutput_a.c",
  "src/secureinput_w.c",
  "src/memcpy_s.c",
  "src/fscanf_s.c",
  "src/vswscanf_s.c",
  "src/secureinput_a.c",
  "src/sprintf_s.c",
  "src/memmove_s.c",
  "src/swscanf_s.c",
  "src/snprintf_s.c",
  "src/vscanf_s.c",
  "src/vswprintf_s.c",
  "src/wcscpy_s.c",
  "src/vfwscanf_s.c",
  "src/memset_s.c",
  "src/wscanf_s.c",
  "src/vwscanf_s.c",
  "src/strtok_s.c",
  "src/wcsncpy_s.c",
  "src/vfscanf_s.c",
  "src/vsscanf_s.c",
  "src/wcstok_s.c",
  "src/securecutil.c",
  "src/gets_s.c",
  "src/swprintf_s.c",
  "src/strcpy_s.c",
  "src/wcscat_s.c",
  "src/strncpy_s.c",
]

include_common = [
  "include",
  "src",
]

ohos_static_library("libHWSecureC") {
  sources = src_libHWSecureC
  include_dirs = include_common
}

ohos_shared_library("libboundscheck") {
  sources = src_libHWSecureC
  include_dirs = include_common
}
'
create_build_gn "huawei_secure_c" "$huawei_secure_c_content" || exit 1

# 为paho.mqtt.c创建BUILD.gn文件
echo "创建paho.mqtt.c/BUILD.gn..."
paho_mqtt_content='
#
# Copyright (c) [2020] Huawei Technologies Co.,Ltd.All rights reserved.
#
# OpenArkCompiler is licensed under the Mulan PSL v1.
# You can use this software according to the terms and conditions of the Mulan PSL v1.
# You may obtain a copy of Mulan PSL v1 at:
#
#     http://license.coscl.org.cn/MulanPSL
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR
# FIT FOR A PARTICULAR PURPOSE.
# See the Mulan PSL v1 for more details.
#

import("//build/ohos.gni")
MQTT_SRC_DIR = "src"

MQTT_AS_SOURCE_FILES = [
    "${MQTT_SRC_DIR}/Base64.c",
    "${MQTT_SRC_DIR}/Clients.c",
    "${MQTT_SRC_DIR}/Heap.c",
    "${MQTT_SRC_DIR}/LinkedList.c",
    "${MQTT_SRC_DIR}/Log.c",
    "${MQTT_SRC_DIR}/Messages.c",
    "${MQTT_SRC_DIR}/MQTTAsync.c",
    "${MQTT_SRC_DIR}/MQTTAsyncUtils.c",
    "${MQTT_SRC_DIR}/MQTTPacket.c",
    "${MQTT_SRC_DIR}/MQTTPacketOut.c",
    "${MQTT_SRC_DIR}/MQTTPersistence.c",
    "${MQTT_SRC_DIR}/MQTTPersistenceDefault.c",
    "${MQTT_SRC_DIR}/MQTTProperties.c",
    "${MQTT_SRC_DIR}/MQTTProtocolClient.c",
    "${MQTT_SRC_DIR}/MQTTProtocolOut.c",
    "${MQTT_SRC_DIR}/MQTTReasonCodes.c",
    "${MQTT_SRC_DIR}/MQTTTime.c",
    "${MQTT_SRC_DIR}/OsWrapper.c",
    "${MQTT_SRC_DIR}/Proxy.c",
    "${MQTT_SRC_DIR}/SHA1.c",
    "${MQTT_SRC_DIR}/Socket.c",
    "${MQTT_SRC_DIR}/SocketBuffer.c",
    "${MQTT_SRC_DIR}/SSLSocket.c",
    "${MQTT_SRC_DIR}/StackTrace.c",
    "${MQTT_SRC_DIR}/Thread.c",
    "${MQTT_SRC_DIR}/Tree.c",
    "${MQTT_SRC_DIR}/utf-8.c",
    "${MQTT_SRC_DIR}/WebSocket.c",
]

ohos_shared_library("libpaho-mqtt3as") {
  sources = MQTT_AS_SOURCE_FILES
  include_dirs = ["./src", "./build"]
  external_deps = [
        "openssl:libcrypto_static",
        "openssl:libssl_static"
  ]
    
  cflags = ["-w", "-fPIC", "-Os", "-fvisibility=hidden", "-DOPENSSL", "-D_GNU_SOURCE", "-DPAHO_MQTT_EXPORTS=1"]
  libs= ["pthread", "dl"]
  ldflags = ["-Wl,-init,MQTTAsync_init"]
}
'
create_build_gn "paho.mqtt.c" "$paho_mqtt_content" || exit 1

# 为libssh创建BUILD.gn文件
echo "创建libssh/BUILD.gn..."
libssh_content='
#
# Copyright (c) [2020] Huawei Technologies Co.,Ltd.All rights reserved.
#
# OpenArkCompiler is licensed under the Mulan PSL v1.
# You can use this software according to the terms and conditions of the Mulan PSL v1.
# You may obtain a copy of Mulan PSL v1 at:
#
#     http://license.coscl.org.cn/MulanPSL
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR
# FIT FOR A PARTICULAR PURPOSE.
# See the Mulan PSL v1 for more details.
#

import("//build/ohos.gni")

src_libHWSecureC = [
"src/agent.c",
"src/auth.c",
"src/base64.c",
"src/bignum.c",
"src/buffer.c",
"src/callbacks.c",
"src/channels.c",
"src/client.c",
"src/config.c",
"src/connect.c",
"src/connector.c",
"src/curve25519.c",
"src/dh.c",
"src/ecdh.c",
"src/error.c",
"src/getpass.c",
"src/init.c",
"src/kdf.c",
"src/kex.c",
"src/known_hosts.c",
"src/knownhosts.c",
"src/legacy.c",
"src/log.c",
"src/match.c",
"src/messages.c",
"src/misc.c",
"src/options.c",
"src/packet.c",
"src/packet_cb.c",
"src/packet_crypt.c",
"src/pcap.c",
"src/pki.c",
"src/pki_container_openssh.c",
"src/poll.c",
"src/session.c",
"src/scp.c",
"src/socket.c",
"src/string.c",
"src/threads.c",
"src/wrapper.c",
"src/external/bcrypt_pbkdf.c",
"src/external/blowfish.c",
"src/external/chacha.c",
"src/external/poly1305.c",
"src/chachapoly.c",
"src/config_parser.c",
"src/token.c",
"src/pki_ed25519_common.c",
"src/threads/noop.c",
"src/threads/pthread.c",
"src/threads/libcrypto.c",
"src/pki_crypto.c",
"src/ecdh_crypto.c",
"src/libcrypto.c",
"src/dh_crypto.c",
"src/pki_ed25519.c",
"src/external/ed25519.c",
"src/external/fe25519.c",
"src/external/ge25519.c",
"src/external/sc25519.c",
"src/sftp.c",
"src/sftpserver.c",
"src/server.c",
"src/bind.c",
"src/bind_config.c",
"src/dh-gex.c",
"src/external/curve25519_ref.c",
]

include_common = [
  "./build",
  "./include/",
  "./include/libssh",
  "./build/include",
  "./build/src",
]

ohos_shared_library("libssh") {
  sources = src_libHWSecureC
  include_dirs = include_common
  external_deps = [
        "openssl:libcrypto_static",
        "openssl:libssl_static"
  ]
  cflags = ["-w", "-std=gnu99", "-fPIC", "-DLIBSSH_EXPORTS", "-D_GNU_SOURCE"]
}
'
create_build_gn "libssh" "$libssh_content" || exit 1

# 为nopoll创建BUILD.gn文件
echo "创建nopoll/BUILD.gn..."
nopoll_content='
#
# Copyright (c) [2020] Huawei Technologies Co.,Ltd.All rights reserved.
#
# OpenArkCompiler is licensed under the Mulan PSL v1.
# You can use this software according to the terms and conditions of the Mulan PSL v1.
# You may obtain a copy of Mulan PSL v1 at:
#
#     http://license.coscl.org.cn/MulanPSL
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR
# FIT FOR A PARTICULAR PURPOSE.
# See the Mulan PSL v1 for more details.
#
import("//build/ohos.gni")

src_nopoll = [
  "src/nopoll.c",
  "src/nopoll_conn.c",
  "src/nopoll_conn_opts.c",
  "src/nopoll_ctx.c",
  "src/nopoll_decl.c",
  "src/nopoll_io.c",
  "src/nopoll_listener.c",
  "src/nopoll_log.c",
  "src/nopoll_loop.c",
  "src/nopoll_msg.c",
  "src/nopoll_win32.c",
]

include_common = [
  "include",
  "src",
]

ohos_shared_library("libnopoll") {
  sources = src_nopoll
  include_dirs = include_common
  external_deps = [
        "openssl:libcrypto_static",
        "openssl:libssl_static"
  ]
  cflags = ["-w"]
}
'
create_build_gn "nopoll" "$nopoll_content" || exit 1

# 为libssh执行cmake命令生成头文件
echo "为libssh生成头文件..."
cd libssh || {
    echo "错误：无法进入libssh目录"
    exit 1
}

mkdir -p build || {
    echo "错误：无法创建build目录"
    exit 1
}

cd build || {
    echo "错误：无法进入build目录"
    exit 1
}

cmake .. \
    -DCMAKE_BUILD_TYPE=Release -DWITH_ZLIB=OFF \
    -DOPENSSL_ROOT_DIR="$SCRIPT_DIR/third_party/openssl" \
    -DOPENSSL_INCLUDE_DIR="$SCRIPT_DIR/third_party/openssl/include" \
    -DOPENSSL_CRYPTO_LIBRARY="$SCRIPT_DIR/out/rk3568/packages/phone/system/lib/libcrypto.z.so" \
    -DHAVE_STRTOULL=1 -DUNIX=1 -DHAVE_POLL=0 -DHAVE_GLOB=0 \
    -DHAVE_OPENSSL_CRYPTO_CTR128_ENCRYPT=1 || {
    echo "错误：cmake命令执行失败"
    exit 1
}

# 返回初始目录
cd "$SCRIPT_DIR/third_party" || {
    echo "错误：无法返回third_party目录"
    exit 1
}

# 为paho.mqtt.c生成VersionInfo.h
echo "为paho.mqtt.c生成VersionInfo.h..."
echo "为paho.mqtt.c生成VersionInfo.h..."
cd paho.mqtt.c || {
    echo "错误：无法进入paho.mqtt.c目录"
    exit 1
}

make build/VersionInfo.h || {
    echo "错误：生成VersionInfo.h失败"
    exit 1
}
if [ ! -f "build/VersionInfo.h" ]; then
    echo "错误：VersionInfo.h文件未生成"
    exit 1
fi

# 返回初始目录
cd "$SCRIPT_DIR/third_party" || {
    echo "错误：无法返回third_party目录"
    exit 1
}

# 为nopoll创建nopoll_config.h
echo "为nopoll创建nopoll_config.h..."
nopoll_config_content='
/*
 * Nopoll Library nopoll_config.h
 * Platform dependant definitions.
 *
 * This is a generated file.  Please modify 'configure.in'
 */

#ifndef __NOPOLL_CONFIG_H__
#define __NOPOLL_CONFIG_H__

/**
 * \addtogroup nopoll_decl_module
 * @{
 */

/**
 * @brief Allows to convert integer value (including constant values)
 * into a pointer representation.
 *
 * Use the oposite function to restore the value from a pointer to a
 * integer: \ref PTR_TO_INT.
 *
 * @param integer The integer value to cast to pointer.
 *
 * @return A \ref noPollPtr reference.
 */
#ifndef INT_TO_PTR
#define INT_TO_PTR(integer)   ((noPollPtr) (long) ((int)integer))
#endif

/**
 * @brief Allows to convert a pointer reference (\ref noPollPtr),
 * which stores an integer that was stored using \ref INT_TO_PTR.
 *
 * Use the oposite function to restore the pointer value stored in the
 * integer value.
 *
 * @param ptr The pointer to cast to a integer value.
 *
 * @return A int value.
 */
#ifndef PTR_TO_INT
#define PTR_TO_INT(ptr) ((int) (long) (ptr))
#endif

/**
 * @brief Allows to get current platform configuration. This is used
 * by Nopoll library but could be used by applications built on top of
 * Nopoll to change its configuration based on the platform information.
 */
#define NOPOLL_OS_UNIX (1)

/**
 * @internal Allows to now if the platform support vasprintf
 * function. Do not use this macro as it is supposed to be for
 * internal use.
 */
#define NOPOLL_HAVE_VASPRINTF (1)

/**
 * @brief Indicates that this platform have support for 64bits.
 */
#define NOPOLL_64BIT_PLATFORM (1)

/**
 * @brief Indicates where we have support for TLSv1.0 support.
 */
#define NOPOLL_HAVE_TLSv10_ENABLED (1)

/**
 * @brief Indicates where we have support for TLSv1.1 support.
 */
#define NOPOLL_HAVE_TLSv11_ENABLED (1)

/**
 * @brief Indicates where we have support for TLSv1.2 support.
 */
#define NOPOLL_HAVE_TLSv12_ENABLED (1)

/**
 * @brief Indicates where we have support for TLS flexible method where the highest TLS version will be negotiated.
 */
#define NOPOLL_HAVE_TLS_FLEXIBLE_ENABLED (1)

/* @} */

#endif
'
cd nopoll/src || {
    echo "错误：无法进入nopoll/src目录"
    exit 1
}

echo "$nopoll_config_content" > nopoll_config.h || {
    echo "错误：无法创建nopoll_config.h文件"
    exit 1
}
# 检查文件是否创建成功
if [ ! -f "nopoll_config.h" ]; then
    echo "错误：nopoll_config.h文件未创建"
    exit 1
fi
echo "所有操作已完成！"
